package com.lynn.salary.web.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lynn.salary.entity.Accessory;
import com.lynn.salary.entity.Article;
import com.lynn.salary.entity.ArticleType;
import com.lynn.salary.pojo.FeedBack;
import com.lynn.salary.service.IAccessoryService;
import com.lynn.salary.service.IArticleService;
import com.lynn.salary.service.IArticleTypeService;
import com.lynn.salary.service.ISysArgumentService;
import com.lynn.salary.util.ObjectFactory;
import com.lynn.salary.util.ToolMethod;

public class ArticleAction extends BaseAction {

	private Article article;
	private FeedBack feedBack;
	private ISysArgumentService sysArgumentService = (ISysArgumentService) ObjectFactory.getBean("sysArgumentService");
	private IArticleTypeService articleTypeService = (IArticleTypeService) ObjectFactory.getBean("articleTypeService");
	private IAccessoryService accessoryService = (IAccessoryService) ObjectFactory.getBean("accessoryService");

	private IArticleService articleService = (IArticleService) ObjectFactory.getBean("articleService");

	private List<ArticleType> articleType;

	private String articleId;
	private String articleTypeId;
	private String articleTypeName;

	private String[] ids;// 批量删除

	private Map<String, Object> detail;
	
	private String elemid;
	private String status;
	private String flag;

	@Override
	public String execute() throws Exception {
		article = new Article();
		article.setAuthor(loginUser.getLoginUser().getId());
		article.setCreateTime(new Date());
		article.setTitle("新建文章");
		article.setContent("<span style=\"font-size:32px;\">请</span>在此输入正文");

		articleType = articleTypeService.findAll();
		article.setType(articleType.get(0).getId());

		article = articleService.save(article);

		return INPUT;
	}
	
	public String showCurStatus() throws Exception{
		article = articleService.getById(article.getId());
		if(article.getTag().contains("发布")){
			status = "发布";
		}else {
			status = "草稿";
		}
		return "curstatus";
	}
	
	public String ajaxpublish() throws Exception{
		
		ids = new String[]{article.getId()};
		if(flag.equals("1")) {
			publish();
		} else {
			undoPublish();
		}
		
		return showCurStatus();
	}

	public String search() throws Exception {
		articleType = articleTypeService.findAll();
		return "search";
	}

	public String showDetail() throws Exception {
		if (articleId == null || articleId.trim().equals("")) {
			detail = notfound();
			return SUCCESS;
		}
		// article = articleService.getById(articleId);

		List<Map<String, Object>> ds = articleService.getPartByCondition(Article.class,
				new String[] { "id", "createTime", "content", "$author#name author", "title" }, "t1.id=? and t1.isDeleted=0 and t1.tag like '%"+Article.PUBLISH+"%'", new Object[] { articleId });
		List<Map<String, Object>> type = articleTypeService.getPartByCondition(ArticleType.class,
				new String[] { "id","name" }, "id=? and isDeleted=0 and tag like '%"+ArticleType.PUBLISH+"%'", new Object[] { articleTypeId });
		
		Map<String,Object> typeData = (type !=null)&&(type.size()==1) ?type.get(0):null;
		if(typeData != null) {
			articleTypeName=(String) type.get(0).get("name");
			articleTypeId=(String) type.get(0).get("id");
		} else {
			articleTypeName = "未知";
			articleTypeId = "";
		}
		
		if (ds != null && ds.size() == 1) {
			detail = ds.get(0);
			detail.put("content", detail.get("content")+"<br/><br/><br/><br/><br/><br/><br/><br/>");
		}

		if (detail == null) {
			detail = notfound();
		}
		
		detail.put("content", insertAccessoryLink((String) detail.get("content")));
		
		return SUCCESS;
	}
	
	private String insertAccessoryLink(String src) throws Exception {
		boolean flag = true;
		while(flag) {
			int s = src.indexOf("@{#");
			int e = 0;
			if(s !=-1) {
				e = src.indexOf("#}", s);
				if(e == -1) {
					flag = false;
					continue;
				}
				String acc =  src.substring(s, e+2);
				String accName = acc.substring(3, acc.length()-2);
				if(accName != null){
					Accessory ay = accessoryService.getByName(accName, new Accessory());
					if(ay == null) {
						flag = false;
						continue;
					}
					String path = request.getContextPath();
					String basePath = request.getScheme() + "://"
							+ request.getServerName() + ":" + request.getServerPort()
							+ path + "/";
					String p = basePath + "download!accessory.do?accessory.id="+ay.getId(); 
					String rid = ToolMethod.getCharAndNumr(8);
					StringBuffer r = new StringBuffer("<a class=\""+rid+"trigger\" href=\"javascript:;\">"+ accName +"</a>");
					r.append("<script>")
					.append("$(document).ready(function(){$('#"+rid+"').jqm({ajax: '"+p+"', trigger: 'a."+rid+"trigger'});")
					.append("})")
					.append("</script>")
					.append("<div class=\"jqmWindow\" id=\""+rid+"\">")
					.append("正在加载... <img src=\""+basePath+"product/images/busy.gif\" alt=\"loading\" />")
					.append("</div>");
					
					
					src = src.replace(acc, r.toString());
				}
				
			} else {
				flag = false;
				continue;
			}
		}
		
		return src;
	}

	private Map<String, Object> notfound() throws Exception {
		String serveEmail=sysArgumentService.getValue("serveEmail");
		Map<String, Object> detail = new HashMap<String, Object>();
		detail.put("id", "-1");
		detail.put(
				"content",
				"<center><br/>此文章可能没有发布，或者已被删除，也可能由于错误的链接把您带到了这里。<br/>无论如何，请您及时与我们取得联系，通过下面的信箱向我们提交这个错误的链接：<br/>服务信箱 : "+serveEmail+"<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><center>");
		detail.put("title", "您需要的文章不存在！");
		detail.put("author", "管理员");
		detail.put("createTime", new Date());
		return detail;
	}

	public String create() throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("id", article.getId());
		data.put("Content", article.getContent());
		data.put("CreateTime", new Date());
		data.put("Title", article.getTitle());
		data.put("Type", article.getType());

		boolean flag;
		try {
			flag = this.articleService.update(data, article.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}

		feedBack = new FeedBack();
		feedBack.setStatusCode("200");
		if (flag) {
			feedBack.setMessage("保存成功");
		} else {
			feedBack.setMessage("保存失败");
		}
		feedBack.setRel("");
		feedBack.setNavTabId("publishNews");
		feedBack.setForwardUrl("");
		feedBack.setCallbackType("");

		return "feedback";
	}

	public String publish() throws Exception {
		boolean flag;
		try {
			flag = articleService.removeTag(ids, Article.DRAFT, new Article());
			if (flag)
				flag = articleService.addTag(ids, Article.PUBLISH, new Article());
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}

		feedBack = new FeedBack();
		feedBack.setStatusCode("200");
		if (flag) {
			feedBack.setMessage("发布成功");
		} else {
			feedBack.setMessage("发布失败");
		}
		feedBack.setRel("");
		feedBack.setNavTabId("seeAllArticle");
		feedBack.setForwardUrl("");
		feedBack.setCallbackType("");

		return "feedback";
	}

	public String undoPublish() throws Exception {
		boolean flag;
		try {
			flag = articleService.removeTag(ids, Article.PUBLISH, new Article());
			if (flag)
				flag = articleService.addTag(ids, Article.DRAFT, new Article());
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}

		feedBack = new FeedBack();
		feedBack.setStatusCode("200");
		if (flag) {
			feedBack.setMessage("撤销成功");
		} else {
			feedBack.setMessage("撤销失败");
		}
		feedBack.setRel("");
		feedBack.setNavTabId("seeAllArticle");
		feedBack.setForwardUrl("");
		feedBack.setCallbackType("");

		return "feedback";
	}

	public String delete() throws Exception {
		boolean flag = articleService.delete(ids, new Article());

		feedBack = new FeedBack();
		feedBack.setStatusCode("200");
		if (flag) {
			feedBack.setMessage("删除成功");
		} else {
			feedBack.setMessage("删除失败");
		}
		feedBack.setRel("");
		feedBack.setNavTabId("seeAllArticle");
		feedBack.setForwardUrl("");
		feedBack.setCallbackType("");

		return "feedback";
	}

	public String edit() throws Exception {
		article = articleService.getById(article.getId());
		articleType = articleTypeService.findAll();
		return INPUT;
	}

	public String seeAll() throws Exception {

		articleType = articleTypeService.findAll();

		return "seeAll";
	}

	public Article getArticle() {
		return article;
	}

	public void setArticle(Article article) {
		this.article = article;
	}

	public IArticleTypeService getArticleTypeService() {
		return articleTypeService;
	}

	public void setArticleTypeService(IArticleTypeService articleTypeService) {
		this.articleTypeService = articleTypeService;
	}

	public List<ArticleType> getArticleType() {
		return articleType;
	}

	public void setArticleType(List<ArticleType> articleType) {
		this.articleType = articleType;
	}

	public IArticleService getArticleService() {
		return articleService;
	}

	public void setArticleService(IArticleService articleService) {
		this.articleService = articleService;
	}

	public FeedBack getFeedBack() {
		return feedBack;
	}

	public void setFeedBack(FeedBack feedBack) {
		this.feedBack = feedBack;
	}

	public String getArticleTypeId() {
		return articleTypeId;
	}

	public void setArticleTypeId(String articleTypeId) {
		this.articleTypeId = articleTypeId;
	}

	public String getArticleId() {
		return articleId;
	}

	public void setArticleId(String articleId) {
		this.articleId = articleId;
	}

	public String[] getIds() {
		return ids;
	}

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	public Map<String, Object> getDetail() {
		return detail;
	}

	public void setDetail(Map<String, Object> detail) {
		this.detail = detail;
	}

	public ISysArgumentService getSysArgumentService() {
		return sysArgumentService;
	}

	public void setSysArgumentService(ISysArgumentService sysArgumentService) {
		this.sysArgumentService = sysArgumentService;
	}

	public String getElemid() {
		return elemid;
	}

	public void setElemid(String elemid) {
		this.elemid = elemid;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getArticleTypeName() {
		return articleTypeName;
	}

	public void setArticleTypeName(String articleTypeName) {
		this.articleTypeName = articleTypeName;
	}
}
